package com.gzc.pm.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import com.gzc.pm.enums.TestItemModuleType;

import cn.skyclass.io.SitePathInfo;
import cn.skyclass.web.SafeRequestValue;

public class InputDataExcelUpload extends HttpServlet {

	private static final long serialVersionUID = -2898214604556843003L;

	/**
	 * Constructor of the object.
	 */
	public InputDataExcelUpload() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		int testItemModule = SafeRequestValue.getSafeRequestIntValue(request, "testItemModule", 0);
		
		boolean isMultipart = FileUpload.isMultipartContent(request);
		if (isMultipart) {
			int maxMemorySize = 4 * 1024 * 1024;
			int maxRequestSize = 10 * 1024 * 1024;
			String uploadTemp = SitePathInfo.getInstance().getWebDataPath();

			// 创建磁盘工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置参数
			factory.setSizeThreshold(maxMemorySize);
			factory.setRepository(new File(uploadTemp));
			// 创建处理工具
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置最大允许的尺寸
			upload.setSizeMax(10 * maxRequestSize);
			upload.setHeaderEncoding("UTF-8");

			List items = new ArrayList();
			// 解析
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e1) {
				e1.printStackTrace();
			}
			Iterator iter = items.iterator();
			Sheet sheet = null;
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
//					String fieldName = item.getFieldName();
//					String fieldValue = item.getString("UTF-8");
				} else {
					try {
						InputStream is = item.getInputStream();
						Workbook wb = Workbook.getWorkbook(is);
						sheet = wb.getSheet(0);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					String templateName = sheet.getCell(0, 0).getContents().trim();
					int moduleValue = TestItemModuleType.getValueByName(templateName);
					
					int rowNum=sheet.getRows();
					int colNum=sheet.getColumns();
					out.println("<excelData>");
					out.println("<type>"+moduleValue+"</type>");
					out.println("<rows>");
					for (int i = 2; i < rowNum; i++) {
						String rowContent = sheet.getCell(0, i).getContents().trim();
						if(StringUtils.isBlank(rowContent)){
							continue;
						}
						
						out.println("<row>");
//						System.out.println("<row>");
						
						for(int j=0;j<colNum;j++){
							String content = sheet.getCell(j, i).getContents().trim();
							if(StringUtils.isBlank(content)){
								break;
							}
							
							out.println("<col"+j+">"+content+"</col"+j+">");
//							System.out.println("<col"+j+">"+content+"</col"+j+">");
						}
						out.println("</row>");
//						System.out.println("</row>");
					}
					out.println("</rows>");
					out.println("</excelData>");
				}
			}
		}
		
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
